package com.nuoniu.sibanyun.controller.crm;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoniu.sibanyun.common.BaseController;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallTask;
import com.nuoniu.sibanyun.entity.dto.CrmCustomerDto;
import com.nuoniu.sibanyun.entity.dto.CrmCustomerFinanceDto;
import com.nuoniu.sibanyun.entity.dto.CrmCustomerSearchDto;
import com.nuoniu.sibanyun.entity.vo.CrmCustomerFinanceVo;
import com.nuoniu.sibanyun.entity.vo.SelectVo;
import com.nuoniu.sibanyun.entity.vo.SimpleCrmCustomerVo;
import com.nuoniu.sibanyun.entity.crm.CrmCollect;
import com.nuoniu.sibanyun.entity.crm.CrmCustomer;
import com.nuoniu.sibanyun.entity.dto.DynamicDto;
import com.nuoniu.sibanyun.service.crm.ICrmCollectService;
import com.nuoniu.sibanyun.service.crm.ICrmCustomerService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallTaskService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 客户基本信息 前端控制器
 * </p>
 *
 * @author baiqiang
 * @since 2020-06-15
 */
@RestController
@RequestMapping("/crm/customer")
@Api(value="客户管理 ",tags={"客户管理"})
public class CrmCustomerController extends BaseController {

    @Autowired
    private ICrmCustomerService customerService;
    @Autowired
    private ICrmCollectService collectService;
    @Autowired
    @Lazy
    private ICrmCallTaskService taskService;

    /**
     * 获取客户列表
     * @author 小啊刚
     * @date 2020/6/19
     */
    @PostMapping("/page")
    @ApiOperation(value = "动态分页查询接口",tags = "APP_客户管理")
    public HttpResult<Page<HashMap<String,Object>>> getCustomerPage(@RequestBody DynamicDto dynamicDto) {
        Page<HashMap<String, Object>> hashMapPage = customerService.CrmDynamicPage(dynamicDto);
        List<HashMap<String, Object>> records = hashMapPage.getRecords();
        if(records.size() == 0){
            //校验 是不是 在其他客户类型中
            String message = customerService.checkCrmName(dynamicDto.getDtos());
            if(StringUtils.isNotBlank(message)){
                throw new NuoNiuException(message);
            }
        }
        return HttpResult.ok(hashMapPage);
    }

    /**
     * 下拉搜索 客户
     * @author 小啊刚
     * @date 2020/6/19
     */
    @PostMapping("/pageForSelect")
    @ApiOperation(value = "下拉搜索 客户",tags = "APP_客户管理")
    public HttpResult<Page<SelectVo>> pageForSelect(@RequestBody CrmCustomerSearchDto crmCustomerSearchDto) {
        return HttpResult.ok(customerService.pageForSelect(crmCustomerSearchDto.getPage(), crmCustomerSearchDto));
    }

    /***************** 客户——财务 开始 2021-02-20 *****************/
    @GetMapping("/pageCrmCustomerFinanceVo")
    @ApiOperation(value = "获取 客户_财务 信息")
    public HttpResult<Page<CrmCustomerFinanceVo>> pageCrmCustomerFinanceVo(Page page, CrmCustomerFinanceDto crmCustomerFinanceDto) {
        return HttpResult.ok(customerService.pageCrmCustomerFinanceVo(page, crmCustomerFinanceDto));
    }

    @PostMapping("/saveFromFinance")
    @ApiOperation(value = "保存 客户_财务 信息")
    public HttpResult saveFromFinance(@RequestBody CrmCustomerFinanceVo crmCustomerFinanceVo) {
        customerService.saveFromFinance(crmCustomerFinanceVo);
        return HttpResult.ok();
    }

    @DeleteMapping("/removeFromFinance")
    @ApiOperation(value = "批量 删除 客户_财务 信息")
    public HttpResult removeFromFinance(@RequestBody Long... ids) {
        customerService.removeFromFinance(ids);
        return HttpResult.ok();
    }
    /***************** 客户——财务 结束 *****************/


    @GetMapping("/pageForVoucher")
    @ApiOperation(value = "单据 选择客户")
    public HttpResult<Page<SimpleCrmCustomerVo>> pageForVoucher(Page page, CrmCustomerSearchDto crmCustomerSearchDto) {
        return HttpResult.ok(customerService.pageForVoucher(page, crmCustomerSearchDto));
    }


    @GetMapping("/detail")
    @ApiOperation(value = "客户详情",tags = "APP_客户管理")
    public HttpResult<CrmCustomer> getDetail(Integer id){
        return HttpResult.ok(customerService.findById(id));
    }

    /**
     * 保存客户基本信息
     */
    @PostMapping(value = "save")
    @ApiOperation(value = "保存客户基本信息",tags = "APP_客户管理")
    synchronized
    public HttpResult save(@RequestBody CrmCustomerDto crmCustomerDto) {
        if(StringUtils.isBlank(crmCustomerDto.getCrmName())) {
            throw new NuoNiuException("客户名称不能为空");
        }

        return HttpResult.ok(customerService.saveCustomer(crmCustomerDto));
    }


    /**
     * 领用客户
     * @author 小啊刚
     * @date 2020/6/20
     */
    @PostMapping("receive")
    @ApiOperation(value = "领用客户",tags = "APP_客户管理")
    public HttpResult receiveCompany(@RequestBody List<Integer> ids) {
        if(ids.size() < 1) {
            throw  new NuoNiuException("请选择要领用用户");
        }

        return HttpResult.ok(customerService.receive("", ids));
    }

    /**
     * 释放客户
     * @author 小啊刚
     * @date 2020/6/20
     */
    @PostMapping("release")
    @ApiOperation(value = "释放客户",tags = "APP_客户管理")
    public HttpResult release(@RequestBody List<Integer> ids) {
        if (ids.size() < 1) {
            throw new NuoNiuException("请选择要释放的客户");
        }

        customerService.release(ids);
        return HttpResult.ok();
    }

    /**
     * 成交客户
     * @author 小啊刚
     * @date 2020/6/20
     */
    @PostMapping("dealSave")
    @ApiOperation(value = "成交客户",tags = "APP_客户管理")
    public HttpResult dealSave(@RequestBody List<Integer> ids) {
        if (ids.size() < 1) {
            throw new NuoNiuException("请选择要成交的客户");
        }

        customerService.dealSave(ids);
        return HttpResult.ok();
    }

    /**
     * 客户退回
     */
    @PostMapping("potentialSave")
    @ApiOperation(value = "客户退回",tags = "APP_客户管理")
    public HttpResult potentialSave(@RequestBody List<Integer> ids) {
        customerService.potentialSave(ids);
        return HttpResult.ok();
    }

    /**
     * 客户共享
     */
    @PostMapping(value = "saveShare")
    @ApiOperation(value = "客户共享",tags = "APP_客户管理")
    public HttpResult saveShare(CrmCustomer crmCustomer, Long[] ids) {
        // 批量共享
        customerService.saveShare(crmCustomer,ids);
        return HttpResult.ok("共享客户成功！");
    }

    /**
     * 客户分配
     * @author 小啊刚
     * @date 2020/6/20
     */
    @GetMapping("distributionSave")
    @ApiOperation(value = "客户分配",tags = "APP_客户管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name="type",value="客户类型：0.线索公海 1.潜在客户 2.成交客户",required=true,paramType="query"),
            @ApiImplicitParam(name="collarUserId",value="分配人ID",required=true,paramType="query"),
            @ApiImplicitParam(name="collarUserName",value="分配人姓名",required=true,paramType="query"),
            @ApiImplicitParam(name="ids",value="客户Ids",required=true,paramType="query"),
    })
    public HttpResult distributionSave(Integer type, Integer collarUserId, String collarUserName, String ids) {
        if(StringUtils.isBlank(ids) || type == null || collarUserId == null || StringUtils.isBlank(collarUserName)) {
            throw new NuoNiuException("数据不全，分配失败");
        }

        customerService.distributionSave(type, collarUserId, collarUserName, ids);
        return HttpResult.ok();
    }

    /**
     * 停用客户
     * @author 小啊刚
     * @date 2020/6/19
     */
    @GetMapping("/disable")
    @ApiOperation(value = "停用客户",tags = "APP_客户管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids",value="客户Ids",required=true,paramType="query"),
            @ApiImplicitParam(name="status",value="状态（2）",required=true,paramType="query"),
    })
    public HttpResult disable(String ids, Integer status) {
        customerService.updateStatus(ids, status);
        return HttpResult.ok();
    }

    /**
     * 启用客户
     * @author 小啊刚
     * @date 2020/6/19
     */
    @GetMapping("/enable")
    @ApiOperation(value = "启用客户",tags = "APP_客户管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids",value="客户Ids",required=true,paramType="query"),
            @ApiImplicitParam(name="status",value="状态（2）",required=true,paramType="query"),
    })
    public HttpResult enable(String ids, Integer status) {
        customerService.updateStatus(ids, status);
        return HttpResult.ok();
    }

//    /**
//     * 删除客户（弃用）
//     * @author 小啊刚
//     * @date 2020/6/19
//     */
//    @GetMapping("/delete")
//    @ResponseBody
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="ids",value="客户Ids",required=true,paramType="query"),
//            @ApiImplicitParam(name="status",value="状态（1）",required=true,paramType="query"),
//    })
//    public HttpResult delete(String ids, Integer status) {
//        customerService.updateStatus(ids, status);
//        return HttpResult.ok();
//    }

    /**
     * 添加收藏
     * @param ids
     * @return
     */
    @PostMapping(value = "collectAdd")
    @ApiOperation(value = "添加收藏",tags = "APP_客户管理")
    public HttpResult collect(@RequestBody List<String> ids) {
        UserInfo userInfo = UserThreadLocal.get();
        for (String id : ids) {
            CrmCollect collect = new CrmCollect();
            collect.setCustomerId(Integer.parseInt(id));
            collect.setCollectUserId(userInfo.getUserId());
            List<CrmCollect> list = collectService.findList(collect);
            if (list.size() > 0) {
                continue;
            }
            collect.setCollectUserName(userInfo.getRealName());
            collect.setCreateUserName(userInfo.getRealName());
            collectService.save(collect);
        }
        return HttpResult.ok("收藏成功");
    }

    /**
     * 取消收藏
     * @param ids
     * @return
     */
    @PostMapping(value = "collectOut")
    @ApiOperation(value = "取消收藏",tags = "APP_客户管理")
    public HttpResult collectOut(@RequestBody List<String> ids) {
        UserInfo userInfo = UserThreadLocal.get();
        for (String id : ids) {
            CrmCollect collect = new CrmCollect();
            collect.setCustomerId(Integer.parseInt(id));
            collect.setCollectUserId(userInfo.getUserId());
            QueryWrapper<CrmCollect> wrapper = new QueryWrapper<>(collect);
            collectService.remove(wrapper);
        }
        return HttpResult.ok("取消收藏成功");
    }

    /**
     * 客户合并
     * @author 小啊刚
     * @date 2020/6/22
     */
    @GetMapping("combineSave")
    @ApiOperation(value = "客户合并")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids",value="被合并客户Ids(多个 逗号隔开)",required=true,paramType="query"),
            @ApiImplicitParam(name="id",value="合并到的客户id",required=true,paramType="query"),
    })
    public HttpResult combineSave(String ids, Integer id) {
        if(StringUtils.isBlank(ids) || id == null) {
           throw new NuoNiuException("请选择要合并的客户");
        }

        customerService.combineSave(ids, id);
        return HttpResult.ok();
    }

    /**
     * 导出数据
     */
    @ApiOperation("导出数据")
    @PostMapping(value = "exportData")
    public void exportData(@RequestBody DynamicDto dynamicDto, HttpServletResponse response) {
        customerService.exportData(dynamicDto, response);
    }

    /**
     * 下载导入数据模板（客户、供应商）
     *      * #  	crm   				客户
     *      * #  	vendor 				供应商
     *      * #	company				往来单位
     *      * # 	linkMan    		    联系人
     *      * #	touch 				联系记录
     *      * #	business			商机
     *      * #	finance 			财务
     *      * #	financeCrm		    客户档案
     */
    @ApiOperation("下载导入数据模板")
    @RequestMapping(value = "importTemplate")
    @ApiImplicitParams({
            @ApiImplicitParam(name="type",value="下载模板类型 crm：客户， vendor：供应商， financeCrm：客户档案，  company:往来单位 ，" +
                    "linkMan：联系人，touch：联系记录，business：商机，finance：财务 " +
                    " 不传默认'客户'",required=true,paramType="query"),
    })

    public void importTemplate(HttpServletResponse response,String source) {
       customerService.importTemplate(response,source);
    }

//    /**
//     * 获取Excel表头字段
//     */
//    @ApiOperation("获取Excel表头字段")
//    @PostMapping("getExcelFiled")
//    public HttpResult getExcelFiled(MultipartFile file) {
//        Map data = new HashMap();
//        List<String> excelFiled = customerService.getExcelFiled(file);
//        //获取客户和联系人字段
//        List<Map<String, String>> crmFiled = customerService.getCrmImportFiled();
//        data.put("excelFiled", excelFiled);
//        data.put("crmFiled", crmFiled);
//        return HttpResult.ok(data);
//    }

    /**
     * 获取Excel表头字段-传参数
     *    crm   				客户
     *    vendor 				供应商
     *    company				往来单位
     *    linkMan    		    联系人
     *    touch 				联系记录
     *    business			    商机
     *    finance 			    财务
     *    financeCrm		    客户档案
     */
    @ApiOperation("获取Excel表头字段(新)")
    @PostMapping("getExcelFiled")
    @ApiImplicitParams({
            @ApiImplicitParam(name="source",value="crm：客户， vendor：供应商， financeCrm：客户档案，  company:往来单位 ，linkMan：联系人，touch：联系记录，business：商机，finance：财务",required=true,paramType="query"),
    })
    public HttpResult getExcelFiledFromCompanyType(MultipartFile file,String source) {
        return HttpResult.ok(customerService.getExcelFiledFromCompanyType(file,source));
    }

    /**
     * crm导入数据
     * companyType ：客户属性：isCustomer（客户），isSupplier（供应商），isFinance（财务），isOther（其他）
     */
    @ApiOperation("导入数据")
    @PostMapping(value = "importData")
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyType",value="客户属性（可自由组合，逗号隔开）：isCustomer（客户），isSupplier（供应商），isFinance（财务），isOther（其他）",required=true,paramType="query"),
    })
    public HttpResult importData(MultipartFile file, String[] excelFiled, String[] dbFiled,String companyType,Boolean isTask,Long taskId) {
        if (file == null) {
            throw new NuoNiuException("请选择导入的数据文件！");
        }
        if(null != taskId){
            CrmCallTask callTask = taskService.detailById(taskId);
            if(null == callTask)throw new NuoNiuException("查询不到任务");
            if(callTask.getBusinessStatus() > 0)throw new NuoNiuException("任务已经关闭，不能添加");
        }
        try {
            /*boolean isUpdateSupport = Global.YES.equals(updateSupport);*/
            Map result = customerService.importData(file, false, excelFiled, dbFiled,companyType,isTask,taskId);
            return HttpResult.ok(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new NuoNiuException("导入数据失败");
        }
    }

    /**
     * 下载失败原因
     */
    @ApiOperation("下载失败原因")
    @PostMapping("downloadFailCause")
    public void downloadFailCause(String[] excelField, String failData, String[] failCause, HttpServletResponse response) throws IOException {
        List<List> listData = JSON.parseArray(failData, List.class);
        ExcelUtils.downloadFailCause(excelField, listData, failCause, response);
    }

//    @ApiOperation("下载 “供应链_客户档案” 导入模板")
//    @GetMapping("downloadImportTemplate")
//    public void downloadImportTemplate(HttpServletResponse response) {
//        customerService.downloadImportTemplate(response);
//    }
//
//    @ApiOperation("“供应链_客户档案”导入")
//    @PostMapping("erpCrmImportData")
//    public HttpResult erpCrmImportData(MultipartFile file) {
//        try {
//            return HttpResult.ok(customerService.erpCrmImportData(file));
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new NuoNiuException("导入数据失败");
//        }
//    }

//    @ApiOperation("导出erp客户数据")
//    @GetMapping("downloadErpCrmData")
//    public void downloadErpCrmData(HttpServletResponse response) {
//        customerService.downloadErpCrmData(response);
//    }


    /*******************  供应商管理 **************************/

    @PostMapping("/saveVendor")
    @ApiOperation(value = "保存 供应商 信息")
    public HttpResult saveVendor(@RequestBody CrmCustomerDto crmCustomerDto) {
        customerService.saveVendor(crmCustomerDto);
        return HttpResult.ok();
    }

    @DeleteMapping("/removeVendor")
    @ApiOperation(value = "批量 删除 供应商 信息")
    public HttpResult removeVendor(String ids) {
        if(StringUtils.isBlank(ids)) {
            throw new NuoNiuException("请选择删除的数据");
        }

        customerService.removeVendor(ids);
        return HttpResult.ok();
    }

    /**
     * 导入 供应商 数据
     */
    @ApiOperation("导入 供应商 数据")
    @PostMapping(value = "importVendorData")
    public HttpResult importVendorData(MultipartFile file, String[] excelFiled, String[] dbFiled) {
        if (file == null) {
            throw new NuoNiuException("请选择导入的数据文件！");
        }

        try {
            Map result = customerService.importVendorData(file, false, excelFiled, dbFiled);
            return HttpResult.ok(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new NuoNiuException("导入数据失败");
        }
    }

}
